<template>
  <div class="image-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <Navigation>素材管理</Navigation>
      </div>

      <div style="margin-bottom: 20px">
        <el-radio-group v-model="isCollected" size="small" @change="hCollect">
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </el-radio-group>

        <el-button
         type="success"
         size="mini"
         style="float:right"
        @click="dialogVisible=true"
         >上传图片素材 </el-button>
      </div>

      <!--
        gutter: 间隔。列与列之间的间隔大小
        :span="4"。一行有24份，它就表示占4份，就表示一行有6列。
      -->
      <el-row :gutter="10">
        <el-col
        :span="4"
        v-for="(img,idx) in images"
        :key="img.id"
        class="img_item">
          <el-image
            style="height: 180px;width: 180px"
            :src="img.url"
            fit="cover"
          ></el-image>
          <div class="option">
            <span
            @click="hSwitchCollect(img)" class="el-icon-star-off" :class="{'red': img.is_collected}"></span>
            <span
            v-show="!isCollected"
            @click="hDelete(img.id, idx)"
            class="el-icon-delete"></span>
          </div>
        </el-col>
      </el-row>

      <!-- 分页
        1.total: 一共有多少条数据 默认情况，它会以每页10条进行计算总页数
        2. current-change事件。当点击页码时，它会触发并会传入当前的页码。
        :disabled="isLoading"
      -->
      <el-pagination
        style="margin-top: 10px"
        background
        layout="prev, pager, next"
        @current-change="hPageChange"
        :total="total_count">
      </el-pagination>
    </el-card>

    <!--
      上传素材图片的对话框
      :visible.sync="dialogVisible"用来控制是否显示对话框
    -->
    <el-dialog
      append-to-body
      title="上传素材"
      :visible.sync="dialogVisible">
<!--
- action： 必选参数，上传的地址：http://ttapi.research.itcast.cn/mp/v1_0/user/images
- headers: 设置上传的请求头部。要携带token
- name：上传的文件字段名。要与接口中要求保持一致。
- show-file-list： 是否显示已上传文件列表
- on-success：文件上传成功时的钩子。`function(response, file, fileList)`
- before-upload: 上传之前对文件进行检测。 -->
      <el-upload
        class="avatar-uploader"
        action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
        name="image"
        :headers="headers"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
      <el-image v-if="imageUrl" :src="imageUrl" @load="hImageLoad" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
import Navigation from '@/components/Navigation.vue'
export default {
  name: 'ImageIndex',
  data () {
    return {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      total_count: null,
      // 切换数据
      isCollected: false,
      images: [],
      dialogVisible: false,
      curPage: 1,
      is_collected: null
    }
  },
  components: {
    Navigation
  },
  created () {
    this.loadImages()
  },
  methods: {
    async loadImages () {
      try {
        const res = await this.$http({
          method: 'GET',
          url: '/mp/v1_0/user/images',
          params: {
            per_page: 10,
            page: this.curPage,
            collect: this.isCollected
          }
        })
        this.images = res.data.data.results
        this.total_count = res.data.data.total_count
      } catch {
        this.$message.error('请求错误')
      }
    },
    // 分页功能-------start
    hPageChange (curPage) {
      this.curPage = curPage
      this.loadImages()
    // 分页功能-------end
    },
    // 用户收藏与奇幻
    hCollect () {
      this.curPage = 1
      this.loadImages()
    },
    hDelete (id, index) {
      this.$confirm('是否删除')
        .then(
          async () => {
            try {
              const res = await this.$http({
                method: 'DELETE',
                url: '/mp/v1_0/user/images/' + id
              })
              console.log(res)
              this.loadImages()
            } catch {
              this.this.$message.error('删除成功')
            }
          }
        ).catch(
          console.log('取消成功')
        )
    },
    hSwitchCollect () {

    },
    handleAvatarSuccess (res, file) {
      // console.log(res, file)
      // 上传成功
      this.imageUrl = res.data.url
      this.$message.success('上传素材成功')
      this.loadImages()
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      // file.size: 大小是字节
      // 1MB = 1024kB
      // 1KB = 1024B
      // 是否小于2
      const isLt2M = (file.size / 1024 / 1024) < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // 如果返回是false,则不会做后续的上传
      return isJPG && isLt2M
    }
  }

}
</script>
<style lang="less" scoped>

.image-container /deep/ .el-card__body{
  padding:30px;
}

// lang: 用来指定样式是用什么语言?(css, less, sass, scss....)
// scoped: 作用域。加这一项与不加这一样有极大的区别
//   - 如果加了，则下面样式是私有的
//   - 如果不加，则下面样式是全局的
  .img_item {
    position: relative;
    box-sizing: border-box;
  }
  .option {
    position: absolute;
    left: 5px;
    width:180px;
    bottom: 5px;
    height: 30px;
    line-height: 30px;
    background: rgba(0, 0, 0, 0.3);
    text-align: center;
    color: #fff;
    span {
      margin: 0 30px;
      cursor: pointer;
    }
    .red{
      color: red;
    }
  }
.avatar-uploader {
    text-align: center;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
</style>
